<script setup lang="ts">
defineOptions({
  name: "EnergyConsumeRank"
});
import { ref, watch, getCurrentInstance, onMounted, nextTick, reactive, toRefs, computed, onUnmounted } from "vue";
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import { PxMessage } from "px-ui";
import { getConsumeCostOverView } from "@/api/energy/consumeCost";
import tableEcharts from "./tableEcharts/index.vue";

interface Props {
  /**  有 title 时传入 */
  title?: string;
  /**  有按钮时传入，传入后会有 btn-click 事件 */
  button?: string;
  /**  模块最低宽度，默认 330px */
  width?: number;
  /**  模块最低高度，默认 200px */
  height?: number;
  /**  是否需要背景阴影，默认为true */
  boxShadow?: boolean;
  /**  是否需要圆角，默认为true */
  borderRidus?: boolean;
  /**  是否暗色，默认为false */
  dark?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: "能耗排行",
  dark: false,
  width: 330,
  height: 200,
  boxShadow: true,
  borderRidus: true
});

interface queryForm {
  queryTimeGranularity?: string;
  level?: string;
  startTime?: string;
  endTime?: string;
}

type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

interface Emits {
  /**  title 右侧按钮点击后触发 */
  (event: "btn-click"): void;
}

const emits = defineEmits<Emits>();

const title_height = computed(() => (props.title ? "38px" : "0px"));
const min_width = computed(() => `${props.width}px`);
const min_height = computed(() => `${props.height}px`);

const energyType = ref("all");

const tablePieKey = ref(Date.now());

const radioOptions = ref<any>([
  {
    label: "all",
    name: "总能耗折标煤",
    size: "small"
  },
  {
    label: "electricity",
    name: "电",
    size: "small"
  },
  {
    label: "water",
    name: "水",
    size: "small"
  },
  {
    label: "ng",
    name: "天然气",
    size: "small"
  },
  {
    label: "steam",
    name: "蒸汽",
    size: "small"
  },
  {
    label: "hot",
    name: "热水",
    size: "small"
  },
  {
    label: "gas",
    name: "大宗气",
    size: "small"
  }
]);

const tableColumns = ref([
  {
    label: "系统",
    prop: "system",
    align: "left"
  },
  {
    label: "总能耗",
    prop: "summaryCost",
    align: "left"
  },
  {
    label: "电",
    prop: "electricityCost",
    align: "left"
  },
  {
    label: "水",
    prop: "waterCost",
    align: "left"
  },
  {
    label: "天然气",
    prop: "ngCost",
    align: "left"
  },
  {
    label: "蒸汽",
    prop: "steamCost",
    align: "left"
  },
  {
    label: "热水",
    prop: "hotCost",
    align: "left"
  },
  {
    label: "大宗气",
    prop: "gasCost",
    align: "left"
  }
]);

const { proxy }: any = getCurrentInstance();

// 定义数据
const dateRange = ref<any>([]);

const yearStart = ref("");
const yearEnd = ref("");
// 可选择区间，initYear传参，不传则所有年份有效，小于0判断一下？
const dateValue = ref<any>({ startYear: new Date().getFullYear(), endYear: new Date().getFullYear() });
// const dateValue = ref<any>({});
// 选完/输入完成的回调
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  dateRange.value = [startYear ? startYear.toString() : "", endYear ? endYear.toString() : ""];
  yearStart.value = `${startYear}-01-01 00:00:00`;
  yearEnd.value = `${endYear}-12-31 23:59:59`;
};

const pageData = ref<any>({});

const costOptions = ref<UtilsEChartsOption>({});

const dataList = ref<any>([]);

const clickHandler = () => emits("btn-click");

const getPageData = async () => {
  const param = {
    level: queryParams.value.level,
    startDate: queryParams.value.startTime,
    endDate: queryParams.value.endTime,
    dimension: queryParams.value.queryTimeGranularity.split("")[0]
  };
  const res: any = await getConsumeCostOverView(param);
  pageData.value = res ? res : {};
  dataList.value =
    (res.costSummaryTable &&
      res.costSummaryTable.sort((a, b) => {
        return b.summaryCost - a.summaryCost;
      })) ||
    [];
  const data: any = dataList.value.map(el => {
    return {
      name: el.system,
      value: el.summaryCost ? Number(el.summaryCost).toFixed(2) : null
    };
  });
  costOptions.value = labelLayoutFn(data);
  tablePieKey.value = Date.now();
};

const labelLayoutFn = (data: Array<dataType>) => {
  const options: UtilsEChartsOption = {
    color: ["#5B8FF9", "#5AD8A6 ", "#FFB910"],
    tooltip: {
      trigger: "item",
      formatter: `{a} <br/>{b}: {c} ({d}%)`
    },
    grid: {
      left: "0px",
      top: "40px",
      right: "10px",
      bottom: "10px",
      containLabel: true
    },
    legend: {
      type: "scroll", // 设置图例分页类型为滚动
      icon: "rect",
      orient: "horizontal", // 水平排列
      data: (data && data.map(el => el.name)) || []
    },
    series: [
      {
        name: "耗能费用排行",
        type: "bar",
        labelLine: {
          length: 30
        },
        label: {
          formatter: `{c|{c}} \n{d|{d}%}`,
          rich: {
            c: {
              fontSize: 16
            },
            d: {
              fontSize: 16,
              fontWeight: "bold"
            }
          }
        },
        data: data || []
      }
    ]
  };
  return options;
};

const queryParams = ref<queryForm>({
  queryTimeGranularity: "Monthly",
  level: ""
});

const queryTypeParams = ref({
  energyType: "Electricity"
});

// 获取当月第一天
const getCurrentMonthF = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d = "01";
  m = m < 10 ? "0" + m : m;
  return [y, m, d].join("-");
};

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d: any = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

const handleChangeFn = (val: string) => {
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  switch (val) {
    case "Daily":
      dateRange.value = [getCurrentMonthF(), getCurrentMonthL()];
      // queryParams.value.startTime = getCurrentMonthF() + " 00:00:00";
      // queryParams.value.endTime = getCurrentMonthL() + " 23:59:59";
      break;
    case "Monthly":
      dateRange.value = [`${year}-${month}`, `${year}-${month}`];
      // queryParams.value.startTime = dateRange.value[0] + "-01 00:00:00";
      // queryParams.value.endTime = dateRange.value[1] + "-31 23:59:59";
      break;
    case "Yearly":
      let yearS = new Date().getFullYear();
      let yearE = new Date().getFullYear();
      yearStart.value = `${yearS}-01-01 00:00:00`;
      yearEnd.value = `${yearE}-12-31 23:59:59`;
      break;
    default:
      break;
  }
};

// 校验时间范围不为空
const checkDate = () => {
  if (queryParams.value.queryTimeGranularity) {
    if (dateRange.value && dateRange.value.length) {
      return true;
    }
    if (queryParams.value.startTime && queryParams.value.endTime) {
      return true;
    }
  }
};

// 获取某月最后一天
const getMonthLastDay = (y, m) => {
  let date = new Date(y, m - 1, "01");
  date.setDate(1);
  date.setMonth(date.getMonth() + 1);
  let cdate = new Date(date.getTime() - 1000 * 60 * 60 * 24);
  return cdate.getDate();
};

const factoryName = ref("");
/** 搜索按钮操作 */
function handleQuery() {
  factoryName.value = queryParams.value.level;
  if (queryParams.value.queryTimeGranularity === "Daily") {
    queryParams.value.startTime = dateRange.value[0] + " 00:00:00";
    queryParams.value.endTime = dateRange.value[1] + " 23:59:59";
    // queryParams.value.startTime =
    //   queryParams.value.startTime.indexOf("00") != -1 ? queryParams.value.startTime : queryParams.value.startTime + " 00:00:00";
    // queryParams.value.endTime = queryParams.value.endTime.indexOf("59") != -1 ? queryParams.value.endTime : queryParams.value.endTime + " 23:59:59";
  } else if (queryParams.value.queryTimeGranularity === "Monthly") {
    queryParams.value.startTime = dateRange.value[0].indexOf("00") != -1 ? dateRange.value[0] : dateRange.value[0] + "-01 00:00:00";
    const d = getMonthLastDay(Number(dateRange.value[1].split("-")[0]), Number(dateRange.value[1].split("-")[1]));
    queryParams.value.endTime = dateRange.value[1].indexOf("59") != -1 ? dateRange.value[1] : dateRange.value[1] + "-" + d + " 23:59:59";
  } else {
    queryParams.value.startTime = yearStart.value;
    queryParams.value.endTime = yearEnd.value;
  }
  console.log(queryParams.value.startTime, queryParams.value.endTime);
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) return;
    if (queryParams.value.queryTimeGranularity) {
      if (!checkDate()) {
        return PxMessage({
          type: "warning",
          message: "时间范围不能为空"
        });
      }
    }
  });
  getPageData();
}
/** 重置按钮操作 */
function resetQuery() {
  initQuery();
}

// 反转数组
const reverseArray = (arr: any[]) => {
  let newArr = [];
  arr.forEach((item: any) => {
    newArr.unshift(item);
  });
  return newArr;
};

const initQuery = () => {
  queryParams.value.queryTimeGranularity = "Monthly";
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  dateRange.value = [`${year}-${month}`, `${year}-${month}`];
  queryParams.value.startTime = getCurrentMonthF() + " 00:00:00";
  queryParams.value.endTime = getCurrentMonthL() + " 23:59:59";
  queryParams.value.level = "";
  getPageData();
};

onMounted(async () => {
  initQuery();
});
</script>

<template>
  <div class="today-task" :class="{ boxShadow, borderRidus, 'model-title-com-dark': dark }">
    <modelTitle v-if="title" :title="title">
      <div class="model-title-slot">
        <px-button v-if="button" type="primary" size="small" plain @click="clickHandler">{{ button }}</px-button>
        <px-form ref="queryRef" class="custom-form-ui inspection-form" :model="queryParams" :inline="true" label-width="100px">
          <px-form-item label="时间维度" prop="dataFormat" style="width: 280px">
            <px-radio-group v-model="queryParams.queryTimeGranularity" style="margin-left: 10px" @change="handleChangeFn">
              <!-- <px-radio size="small" label="Hourly">小时</px-radio> -->
              <px-radio size="small" label="Daily">日</px-radio>
              <px-radio size="small" label="Monthly">月</px-radio>
              <px-radio size="small" label="Yearly">年</px-radio>
            </px-radio-group>
          </px-form-item>
          <px-form-item label="时间范围" style="width: 380px">
            <!-- <px-time-picker
              v-if="queryParams.queryTimeGranularity === 'Hourly'"
              v-model="dateRange"
              is-range
              range-separator="-"
              format="HH"
              value-format="HH"
              start-placeholder="开始小时"
              end-placeholder="结束小时"
            /> -->
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Daily'"
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Monthly'"
              v-model="dateRange"
              type="monthrange"
              value-format="YYYY-MM"
              range-separator="-"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
            />
            <!-- <div v-else-if="queryParams.queryTimeGranularity === 'Yearly'" class="select_year">
              <px-date-picker v-model="queryParams.startTime" value-format="YYYY" type="year" placeholder="开始年份" />
              <span>&nbsp;-&nbsp;</span>
              <px-date-picker v-model="queryParams.endTime" value-format="YYYY" type="year" placeholder="结束年份" />
            </div> -->
            <div v-if="queryParams.queryTimeGranularity === 'Yearly'">
              <yearPicker ref="statisticPicker" :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
            </div>
          </px-form-item>
          <!-- <px-form-item label="厂区">
            <px-select v-model="queryParams.level" clearable placeholder="请选择层级">
              <px-option v-for="item in systemList" :key="item.value" :label="item.name" :value="item.value" />
            </px-select>
          </px-form-item> -->
          <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
          <px-button icon="" @click="resetQuery">重置</px-button>
        </px-form>
      </div>
    </modelTitle>
    <div class="today-task-com" />
  </div>
</template>

<style lang="scss" scoped>
.today-task {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 6px;
  align-items: center;
  width: 100%;
  min-width: v-bind(min_width);
  height: 100%;
  min-height: v-bind(min_height);
  padding: 16px;
  background-color: #fff;

  .model-title-slot {
    display: flex;
    gap: 16px;
    align-items: center;

    .right-text {
      font-weight: 600;
      line-height: 1;
      color: var(--px-color-primary);
    }

    .px-icon {
      cursor: pointer;
    }
  }

  .today-task-com {
    width: 100%;
    height: calc(100% - v-bind(title_height));
  }
}

.px-form-item {
  margin-bottom: 0;
}

.boxShadow {
  box-shadow: 0 0 10px rgb(0 37 86 / 12%);
}

.borderRidus {
  border-radius: 4px;
}

.model-title-com-dark {
  color: #fff;
  background: linear-gradient(90deg, #062e51ff, #001e3bff);
  border: 1px solid #83b2ffff;
  box-shadow: inset 0 0 10px 0 #83b2ffff;

  .title-text {
    color: #fff !important;
  }
}
</style>
